﻿#include "mainwindow.h"
#include <QSurfaceFormat>

MainWindow::MainWindow(QQuickItem *parent)
    :QQuickItem(parent)
    ,m_triangleWindow(0)
    ,m_frame(0)
{
    connect(this, &QQuickItem::windowChanged, this, &MainWindow::handleWindowChanged);
}

MainWindow::~MainWindow()
{
}

//关联信号，在渲染前，先描绘opengl
void MainWindow::sync()
{
    if (!m_triangleWindow) {
        m_triangleWindow = new TriangleWindow();
        connect(window(), &QQuickWindow::beforeRendering, m_triangleWindow, &TriangleWindow::renderNow, Qt::DirectConnection);
    }
    m_triangleWindow->setViewportSize(window()->size() * window()->devicePixelRatio());
    m_triangleWindow->setFrame(m_frame);
}

//清除opengl
void MainWindow::cleanup()
{
    if (m_triangleWindow) {
        delete m_triangleWindow;
        m_triangleWindow = 0;
    }
}

void MainWindow::setFrame(qreal frame)
{
    if(frame == m_frame)
        return;

    m_frame = frame;
    emit frameChanged();
    if(window())
        window()->update();
}

//win初始化时候，链接信号
void MainWindow::handleWindowChanged(QQuickWindow *win)
{
    if (win) {
        //描绘qml前的准备工作
        connect(win, &QQuickWindow::beforeSynchronizing, this, &MainWindow::sync, Qt::DirectConnection);
        //画面非法，释放opengl
        connect(win, &QQuickWindow::sceneGraphInvalidated, this, &MainWindow::cleanup, Qt::DirectConnection);

        //渲染qml前不清画面，保留opengl
        win->setClearBeforeRendering(false);
    }
}
